package org.vacoor.xqq.reply.impl.result;

import com.fasterxml.jackson.databind.JsonNode;
import org.vacoor.xqq.core.bean.Buddy;
import org.vacoor.xqq.core.bean.ClientType;
import org.vacoor.xqq.core.bean.Group;
import org.vacoor.xqq.core.bean.Status;
import org.vacoor.xqq.reply.GroupInfoResolver;
import org.vacoor.xqq.reply.impl.JsonResolver;

/*
 */
public class SimpleGroupInfoResolver extends JsonResolver<Group> implements GroupInfoResolver {

    @Override
    protected Group doResolveResult(JsonNode result) {
        JsonNode groupInfo = result.get("ginfo");
        long gid = groupInfo.get("gid").asLong();
        long code = groupInfo.get("code").asLong();
        String name = groupInfo.get("name").asText();
        JsonNode markNode = groupInfo.get("markname");
        String mark = markNode != null ? markNode.asText() : null;

        Group group = createGroup(gid, name);
        group.setCode(code);
        group.setMark(mark);
        for (JsonNode member : result.get("minfo")) {
            long uin = member.get("uin").asLong();
            String nick = member.get("nick").asText();
            Buddy buddy = createBuddy(uin);
            buddy.setNick(nick);
            group.addMember(buddy);
        }

        for (JsonNode statusInfo : result.get("stats")) {
            long uin = statusInfo.get("uin").asLong();
            int client_type = statusInfo.get("client_type").asInt(-1);
            int status = statusInfo.get("stat").asInt(-1);
            Buddy member = group.getMember(uin);
            if (member == null) {
                continue;
            }
            member.setClientType(ClientType.fromCode(client_type));
            member.setStatus(Status.fromCode(status));
        }
        return group;
    }

    protected Group createGroup(long gid, String name) {
        return new Group(gid, name);
    }

    protected Buddy createBuddy(long uin) {
        return new Buddy(uin);
    }
}
